<route lang="json5">
{
  needLogin: true,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '选择成员',
  },
}
</route>
<template>
  <view class="page-container bg-[#f5f5f5]">
    <!-- 顶部导航栏 -->
    <wd-navbar
      title="选择成员"
      left-arrow
      placeholder
      @click-left="goBack"
      custom-style="background: #fff; border-bottom: none;"
      fixed
      safeAreaInsetTop
    >
      <template #right>
        <wd-button size="small" :round="false" custom-class="custom-success" @click="handleSubmit">
          完成
        </wd-button>
      </template>
    </wd-navbar>
    <!-- 顶部搜索区域 -->
    <view class="bg-white px-30rpx py-12rpx w-full box-border">
      <view class="flex">
        <view class="member-selects">
          <view v-for="member in oldSelected" :key="member.studentId" @click="toggleMember(member)">
            <view v-if="!member.headshot" class="avatar-placeholder flex-center">
              {{ getLastTwoChars(member.name) }}
            </view>
            <image v-else :src="member.headshot" class="student-avatar" mode="aspectFill" />
          </view>
          <view
            v-for="member in selectedMembers"
            :key="member.studentId"
            @click="toggleMember(member)"
          >
            <view v-if="!member.headshot" class="avatar-placeholder flex-center">
              {{ getLastTwoChars(member.name) }}
            </view>
            <image v-else :src="member.headshot" class="student-avatar" mode="aspectFill" />
          </view>
        </view>
        <view class="flex-1 h-82rpx">
          <wd-input
            type="text"
            v-model="keyword"
            no-border
            placeholder="搜索"
            @change="handleSearch"
            custom-class="member-search"
          />
        </view>
      </view>
    </view>

    <!-- 班级列表 -->
    <scroll-view scroll-y class="class-scroll-view">
      <view
        v-for="group in groupedClassGroups"
        :key="group.classId"
        class="class-item"
        @click="handleClassClick(group)"
      >
        <view class="class-content">
          <text class="class-name">{{ group.className }}</text>
          <text class="student-count">({{ group.studentList.length }})</text>
        </view>
        <!-- 学生列表区域 -->
        <view class="student-list-container">
          <wd-index-bar highlight-color="#3670F7">
            <template v-for="letterGroup in group?.letterGroups" :key="letterGroup.letter">
              <!-- 字母索引锚点 -->
              <wd-index-anchor :index="letterGroup.letter">
                {{ letterGroup.letter }}
              </wd-index-anchor>

              <!-- 学生列表 -->
              <view class="student-list">
                <view
                  v-for="student in letterGroup.students"
                  :key="student.studentId"
                  class="student-item"
                  @click="toggleMember(student)"
                >
                  <view class="flex items-center">
                    <wd-checkbox
                      :modelValue="
                        selectedMembers.some((m) => m.studentId === student.studentId) ||
                        oldSelected.some((m) => m.studentId === student.studentId)
                      "
                      custom-class="checkbox-style"
                      :disabled="oldSelected.some((m) => m.studentId === student.studentId)"
                    ></wd-checkbox>
                    <view v-if="!student.headshot" class="avatar-placeholder flex-center">
                      {{ getLastTwoChars(student.name) }}
                    </view>
                    <image
                      v-else
                      :src="student.headshot"
                      class="student-avatar"
                      mode="aspectFill"
                    />
                    <text class="student-name">{{ student.name }}</text>
                  </view>
                </view>
              </view>
            </template>
          </wd-index-bar>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { ClassGroup, IndexedStudent, GroupedClassGroup, LetterGroup } from '@/types/edu'
import pinyin from 'pinyin' // 处理拼音工具
import { inviteGroup, membersGroupInfo } from '@/service/edu/group'
import { getStudentList } from '@/service/edu/lesson/lessonMain'
import { useGroupStore, useUserStore } from '@/store'
const searchWidth = ref('30%')
const selectedMembers = ref<IndexedStudent[]>([])
const oldSelected = ref<IndexedStudent[]>([])
const keyword = ref('')
const groupInfo = ref({
  create: '',
  id: '',
  courseId: '',
  groupId: '',
  showGroupName: '',
  headImageThumb: '',
})

function goBack() {
  uni.navigateBack()
}
function handleSearch() {}
// 数据
const classGroups = ref<ClassGroup[]>([])
const userStore = useUserStore()
const handleMemberInfo = (groupId) => {
  membersGroupInfo(groupId).then((group) => {
    if (group.code === 200) {
      let list = group.data
      if (list && list.length > 0) {
        list.forEach((item) => {
          item.name = item?.showNickName
          item.studentId = item?.userId
          item.headshot = item?.headImage
        })
        list = list.filter((item) => item.userId !== userStore.userInfo.userId)
      }
      oldSelected.value = list
    }
  })
}
function changeMemberInfo(createFriendIds) {
  selectedMembers.value = createFriendIds
}
function getChineseFirstLetter(chinese: string) {
  // 获取第一个汉字
  const firstChar = chinese.charAt(0)
  // 使用 pinyin 转换为拼音
  const pinyinResult = pinyin(firstChar, {
    style: pinyin.STYLE_NORMAL,
  })
  // 获取拼音首字母并转大写
  return pinyinResult[0][0].charAt(0).toUpperCase()
}
// 获取姓名的最后两个字
function getLastTwoChars(name: string) {
  if (name && name.length > 0) {
    return name.slice(-2)
  }
  return name
}
// 处理数据，按班级和字母分组
const groupedClassGroups = computed(() => {
  return classGroups.value.map((group) => {
    // 先给每个学生添加首字母
    const indexedStudents = group.studentList.map((student) => ({
      ...student,
      letter: getChineseFirstLetter(student.name),
    }))
    console.log('indexedStudents====', indexedStudents)

    // 按首字母分组
    const letterGroups = indexedStudents.reduce((groups: LetterGroup[], student) => {
      const existingGroup = groups.find((g) => g.letter === student.letter)
      if (existingGroup) {
        existingGroup.students.push(student)
      } else {
        groups.push({
          letter: student.letter,
          students: [student],
        })
      }
      return groups
    }, [])

    // 对字母组进行排序
    letterGroups.sort((a, b) => a.letter.localeCompare(b.letter))

    // 对每个字母组内的学生按姓名排序
    letterGroups.forEach((group) => {
      group.students.sort((a, b) => a.name.localeCompare(b.name))
    })

    return {
      ...group,
      letterGroups,
    }
  })
})
console.log('indexedClassGroups====', groupedClassGroups.value)

// 计算搜索框宽度
const updateSearchWidth = () => {
  const baseWidth = 750 // 屏幕基准宽度
  const minWidth = 120 // 最小搜索框宽度
  const tagWidth = 140 // 每个选中标签的宽度
  const totalTagWidth = selectedMembers.value.length * tagWidth
  const remainingWidth = baseWidth - totalTagWidth
  searchWidth.value = `${Math.max(minWidth, remainingWidth)}rpx`
}

// 选择/取消选择成员
const toggleMember = (student: IndexedStudent) => {
  const disabledType = oldSelected.value.some((m) => m.studentId === student.studentId)
  if (!disabledType) {
    const index = selectedMembers.value.findIndex((m) => m.studentId === student.studentId)
    if (index === -1) {
      selectedMembers.value.push(student)
    } else {
      selectedMembers.value.splice(index, 1)
    }
    updateSearchWidth()
  }
}

// 新增状态
const showStudentList = ref(false)
const currentClass = ref<GroupedClassGroup | null>(null)

// 处理班级点击
const handleClassClick = (group: GroupedClassGroup) => {
  currentClass.value = group
  showStudentList.value = true
}

onLoad(async () => {
  const pages = getCurrentPages()
  const currentPage: any = pages[pages.length - 1]
  const options = currentPage.$page?.options || currentPage?.options || currentPage.$route.query
  if (options) {
    if (options.courseId) {
      groupInfo.value.courseId = options.courseId
      await getStudentList({
        lessonId: options.courseId,
      }).then((res: any) => {
        if (res.code === 200) {
          classGroups.value = res.data
        }
      })
    }
    if (options.groupId) {
      groupInfo.value.groupId = options.groupId
      await handleMemberInfo(options.groupId)
    }
    if (options.create) {
      groupInfo.value.create = options.create
      if (options.create === '1') {
        changeMemberInfo(groupStore.createFriendIds)
      }
    }
  }
})
// 处理完成按钮点击
const groupStore = useGroupStore()
function handleSubmit() {
  console.log('selectedMembers.value=====', selectedMembers.value)
  uni.showModal({
    title: '提示',
    content: '确定邀请进群吗？',
    success: async (res) => {
      try {
        if (res.confirm) {
          console.log('请求====', groupInfo.value.create)
          if (groupInfo.value.create === '1') {
            groupStore.setFriendIds(selectedMembers.value)
            groupStore.setCreateType(true)
            uni.navigateBack()
          } else {
            groupStore.setCreateType(false)
            groupStore.setFriendIds([])
            inviteGroup({
              groupId: groupInfo.value.groupId,
              friendIds: selectedMembers.value.map((item) => item.studentId),
            }).then((data) => {
              if (data.code === 200) {
                uni.navigateBack()
              }
            })
          }
        }
      } catch (e) {
        console.error('删除失败', e)
      } finally {
        console.log('请求')
      }
    },
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
}

.fixed-top {
  position: fixed;
  top: var(--window-top);
  right: 0;
  left: 0;
  z-index: 99;
}

.member-tag {
  font-size: 26rpx;
}

.student-avatar,
.avatar-placeholder {
  width: 82rpx;
  height: 82rpx;
  margin-right: 16rpx;
  border-radius: 12rpx;
}

.avatar-placeholder {
  font-size: 28rpx;
  color: #fff;
  background-color: #3670f7;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.class-title {
  padding: 20rpx 32rpx;
  font-size: 30rpx;
  font-weight: 500;
  background-color: #f5f5f5;
}

.student-list {
  background-color: #fff;
}

.student-item {
  padding: 24rpx 32rpx;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.student-name {
  margin-left: 24rpx;
  font-size: 26rpx;
  color: #333;
}

.checkbox-style {
  width: 46rpx !important;
  height: 46rpx !important;
  margin-right: 24rpx;
}
:deep(.wd-checkbox__shape) {
  width: 46rpx !important;
  height: 46rpx !important;
}

:deep(.wd-index-anchor) {
  height: 48rpx;
  padding: 12rpx 32rpx;
  font-size: 24rpx;
  line-height: 48rpx;
  color: #666;
  background-color: #f5f5f5;
}

.class-scroll-view {
  height: calc(100vh - 180rpx);
  background-color: #fff;
}

.class-item {
  padding: 12rpx 32rpx;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.class-content {
  display: flex;
  align-items: center;
  padding: 12rpx 8rpx;
  font-weight: bold;
  border-bottom: 1rpx solid #edf2fa;
}

.class-name {
  margin-right: 12rpx;
  font-size: 30rpx;
  color: #1a1a1a;
}

.student-count {
  font-size: 30rpx;
  color: #1a1a1a;
}

.student-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-header {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.popup-title {
  flex: 1;
  margin-left: -40rpx; /* 抵消返回按钮的宽度，使标题居中 */
  font-size: 34rpx;
  font-weight: 500;
  text-align: center;
}

.header-right {
  min-width: 40rpx;
}

.done-text {
  font-size: 28rpx;
  color: #3670f7;
}

.student-list-container {
  flex: 1;
  overflow-y: auto;
}

.member-search {
  height: 82rpx !important;
  margin-left: 8rpx;
  font-size: 36rpx !important;
  color: #b2b5bd;
}
:deep(.wd-input.is-no-border .wd-input__inner) {
  height: 82rpx !important;
}
.member-selects {
  display: flex;
  max-width: 80%;
  overflow-y: auto;
}
</style>
